<template>
  <div class="app-container page-flex">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-4">
        <el-card shadow="hover" class="search-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable @change="handleQuery">
                <el-option v-for="template in businessTypeOptions" :key="template.templateType"
                  :label="template.templateName" :value="template.templateType" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请人" prop="applicantId">
              <el-select
                :model-value="selectedSearchApplicant ? selectedSearchApplicant.userName || selectedSearchApplicant.nickName : ''"
                placeholder="请选择申请人" style="width: 240px" clearable @click="showSearchApplicantSelector = true"
                @clear="clearSearchApplicant">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchApplicantSelector = true">选择申请人</el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态" prop="approvalStatus">
              <el-select v-model="queryParams.approvalStatus" placeholder="请选择审核状态" style="width: 240px" clearable>
                <el-option v-for="item in approval_commit_status" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="提交时间" prop="submitTime" style="width: 308px">
              <el-date-picker v-model="submitDateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item label="完成时间" prop="finishTime" style="width: 308px">
              <el-date-picker v-model="finishDateRange" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"></el-date-picker>
            </el-form-item>
            <el-form-item style="margin-left: auto">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" class="table-card">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="ApprovalInstanceList" border height="100%" class="flex-table">
        <el-table-column label="业务类型" align="center" prop="businessType" width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ getBusinessTypeName(scope.row.businessType) }}
          </template>
        </el-table-column>
        <el-table-column label="业务标题" align="center" prop="businessTitle" show-overflow-tooltip />
        <el-table-column label="申请人" align="center" prop="applicantName" width="120" show-overflow-tooltip />
        <el-table-column label="当前阶段" align="center" prop="approvalCurrentStage" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.approvalCurrentStage" type="primary">
              第{{ scope.row.approvalCurrentStage }}阶段
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="阶段总数" align="center" prop="stageCount" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.stageCount > 0" type="info">{{ scope.row.stageCount }} 个阶段</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="是否使用模板" align="center" prop="isTemplate" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.isTemplate === '1'" type="success">使用</el-tag>
            <el-tag v-else type="info">未使用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="submitTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.submitTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成时间" align="center" prop="finishTime" width="150">
          <template #default="scope">
            <span v-if="scope.row.finishTime">{{ parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            <span v-else style="color: #909399;">未完成</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="approvalStatus" width="120">
          <template #default="scope">
            <dict-tag :options="approval_commit_status" :value="scope.row.approvalStatus" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <el-tooltip content="编辑流程" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)"
                v-hasPermi="['approval:instance:edit']">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-show="total > 0">
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
          :page-sizes="[10, 20, 30, 50]" @pagination="getList" />
      </div>
    </el-card>

    <!-- 流程编辑对话框 -->
    <el-dialog title="流程编辑" v-model="viewDialog.visible" width="1400px" append-to-body>
      <div v-if="viewData">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border size="large" class="mb-4">
          <el-descriptions-item label="业务类型">
            {{ getBusinessTypeName(viewData.businessType) }}
          </el-descriptions-item>
          <el-descriptions-item label="业务ID">
            {{ viewData.businessId }}
          </el-descriptions-item>
          <el-descriptions-item label="业务标题" :span="2">
            {{ viewData.businessTitle }}
          </el-descriptions-item>
          <el-descriptions-item label="是否使用模板">
            <el-tag v-if="viewData.isTemplate === '1'" type="success">使用</el-tag>
            <el-tag v-else type="info">未使用</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="模板ID">
            {{ viewData.templateId || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ viewData.remark || '暂无备注' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 自定义审核流程展示 -->
        <el-card class="mb-4" v-loading="flowLoading">
          <template #header>
            <div class="card-header">
              <span class="title">审核流程详情</span>
              <el-tag v-if="approvalStages.length > 0" type="primary" size="large">
                共 {{ approvalStages.length }} 个阶段
              </el-tag>
              <el-tag v-else type="info" size="large">暂无审核流程</el-tag>
            </div>
          </template>

          <!-- 审核流程步骤 -->
          <el-steps :active="getCurrentStepIndex()" align-center class="mb-6" v-if="approvalStages.length > 0">
            <el-step v-for="stage in approvalStages" :key="stage.id" :title="stage.stageName"
              :description="getStageDescription(stage)" :status="getStageStatus(stage)" :icon="getStageIcon(stage)" />
          </el-steps>

          <!-- 详细审核信息 -->
          <div class="approval-details" v-if="approvalStages.length > 0">
            <el-collapse v-model="expandedStages" class="stage-collapse">
              <el-collapse-item v-for="stage in approvalStages" :key="stage.id" :name="stage.id"
                class="stage-collapse-item" :class="{ 'current-stage': stage.isCurrent }">
                <template #title>
                  <div class="stage-header-compact">
                    <div class="stage-info-compact">
                      <span class="stage-number-compact">第{{ stage.stageSort }}阶段</span>
                      <span class="stage-name-compact">{{ stage.stageName }}</span>
                      <dict-tag :options="approval_commit_status" :value="stage.approvalStatus" class="ml-2" />
                      <el-tag v-if="stage.isCurrent" type="warning" size="small" class="ml-1">当前阶段</el-tag>
                      <span v-if="stage.approvalRecords && stage.approvalRecords.length > 0" class="approver-count">
                        ({{ stage.approvalRecords.length }}人)
                      </span>
                    </div>
                  </div>
                </template>

                <!-- 阶段描述 -->
                <div v-if="stage.stageDescription" class="stage-desc-expanded">
                  {{ stage.stageDescription }}
                </div>

                <!-- 审核人员列表 -->
                <div v-if="stage.approvalRecords && stage.approvalRecords.length > 0" class="approvers-list-compact">
                  <div class="approver-cards-compact">
                    <el-tooltip v-for="record in stage.approvalRecords" :key="record.id"
                      :content="getTooltipContent(record)" placement="top" :disabled="!getTooltipContent(record)"
                      raw-content>
                      <div class="approver-card-compact" :class="getApproverCardClass(record.approvalResult)">
                        <div class="approver-avatar">
                          <el-icon class="approver-icon-compact">
                            <User />
                          </el-icon>
                        </div>
                        <div class="approver-info-compact">
                          <div class="approver-name-compact">
                            {{ record.approverName || `审核人${record.approverId}` }}
                          </div>
                          <div class="approver-status-compact">
                            <dict-tag :options="approval_record_status" :value="record.approvalResult" size="small" />
                          </div>
                          <div v-if="record.approvalTime" class="approval-time-compact">
                            {{ parseTime(record.approvalTime, '{m}-{d} {h}:{i}') }}
                          </div>
                        </div>
                      </div>
                    </el-tooltip>
                  </div>
                </div>
                <div v-else class="no-approvers-compact">
                  <el-empty description="暂未配置审核人员" :image-size="40" />
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else class="no-approval-flow">
            <el-empty description="该项目暂未配置审核流程" :image-size="100" />
          </div>
        </el-card>
      </div>

      <template #footer>
        <div>
          <el-button type="warning" :disabled="!viewData || viewData.approvalStatus !== '2'" @click="showRollbackDialog"
            :loading="rollbackLoading">
            回退流程
          </el-button>
          <el-button @click="viewDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回退选择对话框 -->
    <el-dialog title="选择回退阶段" v-model="rollbackDialog.visible" width="600px" append-to-body>
      <div v-if="rollbackDialog.visible">
        <el-alert title="回退说明" type="info" :closable="false" class="mb-4">
          <template #default>
            <p>请选择要回退到的阶段。回退后，所选阶段及之后的所有审核通过和审核中的阶段都将重新审核。</p>
            <p>注意：</p>
            <ul style="margin: 8px 0; padding-left: 20px;">
              <li>只能回退到当前阶段及之前的阶段</li>
              <li>当前阶段（审核中）和审核通过的阶段可以被重新创建</li>
              <li>审核不通过的阶段将被跳过，不会重新审核</li>
            </ul>
          </template>
        </el-alert>

        <el-radio-group v-model="selectedRollbackStage" class="rollback-stage-list">
          <el-radio v-for="stage in availableRollbackStages" :key="stage.id" :label="stage.viewSort"
            :disabled="stage.viewSort > currentStageSort" class="rollback-stage-item">
            <div class="stage-option-simple">
              <div class="stage-name-simple">{{ stage.stageName }}</div>
              <div class="stage-status-simple">
                <dict-tag :options="approval_commit_status" :value="stage.approvalStatus" size="small" />
                <el-tag v-if="stage.viewSort === currentStageSort" type="warning" size="small"
                  class="ml-1">当前阶段</el-tag>
              </div>
            </div>
          </el-radio>
        </el-radio-group>
      </div>

      <template #footer>
        <div>
          <el-button @click="rollbackDialog.visible = false">取 消</el-button>
          <el-button type="warning" @click="handleRollbackConfirm" :disabled="!selectedRollbackStage"
            :loading="rollbackLoading">
            确认回退
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 搜索条件用的申请人选择器 -->
    <UserSelector v-model:visible="showSearchApplicantSelector" title="选择申请人"
      :selected-user-ids="queryParams?.applicantId" :selected-user-names="selectedSearchApplicantName" :multiple="false"
      @confirmWithIds="handleSearchApplicantConfirm" @cancel="handleSearchApplicantCancel" />
  </div>
</template>

<script setup name="ApprovalFlow" lang="ts">
import { listApprovalInstance, getActiveTemplatesForQuery, rollbackApprovalToStage, displayApprovalFlow } from '@/api/other/approval/index';
import { ApprovalInstanceVo } from '@/api/other/approval/types';
import { Edit, User, Check, Close } from '@element-plus/icons-vue';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { approval_commit_status, approval_record_status } = toRefs<any>(proxy?.useDict('approval_commit_status', 'approval_record_status'));

const ApprovalInstanceList = ref<ApprovalInstanceVo[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const businessTypeOptions = ref<any[]>([]);

// 搜索条件申请人选择相关
const showSearchApplicantSelector = ref(false);
const selectedSearchApplicant = ref(null);
const selectedSearchApplicantName = ref('');

// 时间范围选择
const submitDateRange = ref<[DateModelType, DateModelType]>(['', '']);
const finishDateRange = ref<[DateModelType, DateModelType]>(['', '']);

// 回退操作
const rollbackLoading = ref(false);
// 流程加载状态
const flowLoading = ref(false);
// 审核阶段数据
const approvalStages = ref<any[]>([]);
const expandedStages = ref<any[]>([]);

const queryFormRef = ref<ElFormInstance>();

const viewDialog = reactive({
  visible: false
});

const viewData = ref<ApprovalInstanceVo | null>(null);

// 回退对话框相关
const rollbackDialog = reactive({
  visible: false
});

const selectedRollbackStage = ref<number | null>(null);
const availableRollbackStages = ref<any[]>([]);
const currentStageSort = ref<number>(0);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    businessType: undefined,
    applicantId: undefined,
    approvalStatus: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);


/** 获取业务类型选项 */
const getBusinessTypeOptions = async () => {
  try {
    const res = await getActiveTemplatesForQuery();
    businessTypeOptions.value = res.data || [];
  } catch (error) {
    console.error('获取业务类型选项失败:', error);
    businessTypeOptions.value = [];
  }
};

/** 根据业务类型获取模板名称 */
const getBusinessTypeName = (businessType: string) => {
  const template = businessTypeOptions.value.find(item => item.templateType === businessType);
  return template ? template.templateName : businessType;
};

/** 处理搜索条件申请人选择确认 */
const handleSearchApplicantConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchApplicant.value = data.users[0];
    selectedSearchApplicantName.value = data.userNames || '';

    if (queryParams.value) {
      queryParams.value.applicantId = data.userIds || '';
    }
  } else {
    selectedSearchApplicant.value = null;
    selectedSearchApplicantName.value = '';
    if (queryParams.value) {
      queryParams.value.applicantId = '';
    }
  }

  showSearchApplicantSelector.value = false;
};

/** 取消搜索条件申请人选择 */
const handleSearchApplicantCancel = () => {
  showSearchApplicantSelector.value = false;
};

/** 清空搜索条件申请人选择 */
const clearSearchApplicant = () => {
  selectedSearchApplicant.value = null;
  selectedSearchApplicantName.value = '';
  if (queryParams.value) {
    queryParams.value.applicantId = '';
  }
};

/** 查询审核实例列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };

    // 处理提交时间范围
    proxy?.addDateRange(params, submitDateRange.value, 'SubmitTime');
    // 处理完成时间范围
    proxy?.addDateRange(params, finishDateRange.value, 'FinishTime');

    const res = await listApprovalInstance(params);
    ApprovalInstanceList.value = (res as any).rows || [];
    total.value = (res as any).total || 0;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  // 重置时间范围
  submitDateRange.value = ['', ''];
  finishDateRange.value = ['', ''];

  // 重置申请人选择
  selectedSearchApplicant.value = null;
  selectedSearchApplicantName.value = '';

  // 重置查询参数
  queryParams.value.applicantId = undefined;
  queryParams.value.approvalStatus = undefined;
  queryParams.value.params = {};

  queryFormRef.value?.resetFields();
  handleQuery();
};


/** 编辑按钮操作 */
const handleEdit = async (row: ApprovalInstanceVo) => {
  viewData.value = row;
  viewDialog.visible = true;

  // 加载审核流程数据
  await loadApprovalFlowData(row.businessType, row.businessId);
};

/** 加载审核流程数据 */
const loadApprovalFlowData = async (businessType: string, businessId: string | number) => {
  if (!businessType || !businessId) return;

  try {
    flowLoading.value = true;
    const res = await displayApprovalFlow(businessType, businessId.toString());
    const data = res.data;

    if (data) {
      // 处理审核阶段数据（后端已经根据viewSort设置了isCurrent字段）
      approvalStages.value = data.approvalStageVos || [];

      // 设置当前阶段序号
      currentStageSort.value = data.approvalCurrentStage || 0;

      // 初始化展开状态
      expandedStages.value = [];
    } else {
      approvalStages.value = [];
      currentStageSort.value = 0;
    }
  } catch (error) {
    console.error('获取审核流程数据失败:', error);
    approvalStages.value = [];
    currentStageSort.value = 0;
  } finally {
    flowLoading.value = false;
  }
};

/** 获取当前步骤索引 */
const getCurrentStepIndex = () => {
  if (viewData.value) {
    return (viewData.value.approvalCurrentStage || 1) - 1;
  }
  const currentStage = approvalStages.value.find((stage) => stage.isCurrent);
  return currentStage ? currentStage.viewSort - 1 : approvalStages.value.length;
};

/** 获取阶段描述 */
const getStageDescription = (stage: any) => {
  const statusOption = approval_commit_status.value?.find((option) => option.value === stage.approvalStatus);
  const statusText = statusOption?.label || '未知状态';
  return stage.stageDescription ? `${stage.stageDescription} (${statusText})` : statusText;
};

/** 获取阶段状态 */
const getStageStatus = (stage: any) => {
  const status = stage.approvalStatus;
  switch (status) {
    case '3':
      return 'finish'; // 审核通过
    case '4':
      return 'error'; // 审核不通过
    case '2':
      return 'process'; // 审核中
    case '1':
      return 'wait'; // 已提交
    default:
      return 'wait'; // 默认等待
  }
};

/** 获取阶段图标 */
const getStageIcon = (stage: any) => {
  const status = stage.approvalStatus;
  switch (status) {
    case '3':
      return Check;
    case '4':
      return Close;
    default:
      return undefined;
  }
};

/** 获取审核人卡片样式类 */
const getApproverCardClass = (result: string) => {
  switch (result) {
    case '1':
      return 'approved';
    case '2':
      return 'rejected';
    default:
      return 'waiting';
  }
};

/** 获取tooltip内容 */
const getTooltipContent = (record: any) => {
  if (!record.approvalOpinion) return '';

  let content = `<div style="max-width: 300px;">
    <div style="font-weight: bold; margin-bottom: 8px;">${record.approverName || `审核人${record.approverId}`}</div>`;

  if (record.approvalTime) {
    content += `<div style="color: #909399; font-size: 12px; margin-bottom: 8px;">
      ${parseTime(record.approvalTime, '{y}-{m}-{d} {h}:{i}')}
    </div>`;
  }

  content += `<div style="line-height: 1.6; margin-top: 8px;">
  <div style="color: #606266; font-weight: 500; margin-bottom: 4px; font-size: 12px;">
    审核意见：
    <span style="color: #909399; font-weight: normal;">${record.approvalOpinion}</span>
  </div>
</div>`;

  return content;
};

/** 显示回退选择对话框 */
const showRollbackDialog = () => {
  if (!viewData.value) return;

  // 检查状态，只有审核中状态才能回退
  if (viewData.value.approvalStatus !== '2') {
    proxy?.$modal.msgWarning('只有审核中状态才能回退');
    return;
  }

  // 设置可回退的阶段（当前阶段及之前的阶段，包含审核通过和审核中的阶段）
  // 现在使用viewSort来比较阶段顺序
  availableRollbackStages.value = approvalStages.value.filter(stage =>
    stage.viewSort <= currentStageSort.value &&
    (stage.approvalStatus === '3' || stage.approvalStatus === '2') // 审核通过或审核中的阶段
  );

  // 默认选择当前阶段
  selectedRollbackStage.value = currentStageSort.value;

  rollbackDialog.visible = true;
};

/** 确认回退操作 */
const handleRollbackConfirm = async () => {
  if (!viewData.value || !selectedRollbackStage.value) return;

  try {
    // 找到对应的stageSort值用于显示
    const targetStage = availableRollbackStages.value.find(stage => stage.viewSort === selectedRollbackStage.value);
    if (!targetStage) {
      proxy?.$modal.msgError('未找到目标回退阶段');
      return;
    }
    
    await proxy?.$modal.confirm(`是否确认回退到第${targetStage.stageSort}阶段？回退后，该阶段及之后的所有审核通过和审核中的阶段都将重新审核，审核不通过的阶段将被跳过。`);

    rollbackLoading.value = true;

    // 调用新的回退接口，传入instanceId和viewSort值（反映真实的阶段显示顺序）
    await rollbackApprovalToStage(viewData.value.id, selectedRollbackStage.value);

    proxy?.$modal.msgSuccess('审核回退成功');

    // 关闭对话框并刷新列表
    rollbackDialog.visible = false;
    viewDialog.visible = false;
    await getList();
  } catch (error) {
    console.error('审核回退失败:', error);
    if (error !== 'cancel') {
      proxy?.$modal.msgError('审核回退失败，请重试');
    }
  } finally {
    rollbackLoading.value = false;
  }
};


onMounted(() => {
  getBusinessTypeOptions();
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-flex {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 40px);
}

.table-card {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.table-card :deep(.el-card__body) {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.flex-table {
  flex: 1;
}

.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 回退阶段选择样式 */
.rollback-stage-list {
  width: 100%;
}

.rollback-stage-item {
  width: 100%;
  margin-bottom: 8px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px 16px;
  transition: all 0.3s ease;
}

.rollback-stage-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.rollback-stage-item.is-disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.stage-option-simple {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.stage-name-simple {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.stage-status-simple {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 审核流程展示样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

/* 折叠面板样式 */
.stage-collapse {
  border: none;
}

.stage-collapse :deep(.el-collapse-item) {
  margin-bottom: 16px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  overflow: hidden;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.stage-collapse :deep(.el-collapse-item.current-stage) {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.stage-collapse :deep(.el-collapse-item__header) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: none;
  padding: 16px 20px;
  font-weight: 500;
  transition: background 0.2s ease;
}

.stage-collapse :deep(.el-collapse-item__header:hover) {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
}

.stage-collapse :deep(.el-collapse-item__arrow) {
  color: #409eff;
  font-weight: bold;
  transition: transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.stage-collapse :deep(.el-collapse-item__wrap) {
  border: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.stage-collapse :deep(.el-collapse-item__content) {
  padding: 0 20px 20px;
  background: #fff;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 紧凑型阶段标题 */
.stage-header-compact {
  width: 100%;
}

.stage-info-compact {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stage-number-compact {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.stage-name-compact {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.approver-count {
  color: #909399;
  font-size: 12px;
  font-weight: normal;
}

/* 展开后的阶段描述 */
.stage-desc-expanded {
  background: #f5f7fa;
  padding: 12px 16px;
  border-radius: 6px;
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
  margin-top: 16px;
  margin-bottom: 16px;
  border-left: 3px solid #409eff;
}

/* 紧凑型审核人员列表 */
.approvers-list-compact {
  .approver-cards-compact {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: 10px;

    .approver-card-compact {
      background: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 6px;
      padding: 10px;
      transition: all 0.3s ease;
      cursor: pointer;
      position: relative;

      &:hover {
        border-color: #409eff;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
        transform: translateY(-2px);
      }

      &.approved {
        border-color: #67c23a;
        background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);

        &:hover {
          border-color: #67c23a;
          box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
        }
      }

      &.rejected {
        border-color: #f56c6c;
        background: linear-gradient(135deg, #fef0f0 0%, #fde2e2 100%);

        &:hover {
          border-color: #f56c6c;
          box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
        }
      }

      &.waiting {
        border-color: #e6a23c;
        background: linear-gradient(135deg, #fdf6ec 0%, #faecd8 100%);

        &:hover {
          border-color: #e6a23c;
          box-shadow: 0 2px 8px rgba(230, 162, 60, 0.2);
        }
      }

      .approver-avatar {
        display: flex;
        justify-content: center;
        margin-bottom: 6px;

        .approver-icon-compact {
          width: 28px;
          height: 28px;
          background: #409eff;
          color: white;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
        }
      }

      .approver-info-compact {
        text-align: center;

        .approver-name-compact {
          font-weight: 500;
          color: #303133;
          font-size: 12px;
          margin-bottom: 4px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .approver-status-compact {
          margin-bottom: 3px;

          :deep(.el-tag) {
            font-size: 10px;
            height: 18px;
            line-height: 16px;
            padding: 0 6px;
          }
        }

        .approval-time-compact {
          color: #909399;
          font-size: 10px;
          line-height: 1.2;
        }
      }
    }
  }
}

/* 无审核人员状态 */
.no-approvers-compact {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.no-approval-flow {
  text-align: center;
  padding: 40px;
}

.ml-1 {
  margin-left: 4px;
}

.ml-2 {
  margin-left: 8px;
}
</style>
